import os
import docx
import shutil


def transFile(orig_path, new_path):
    files = []
    for file in os.listdir(orig_path):
        if file.endswith('.docx'):
            files.append(orig_path + '/' + file)

    for file in files:
        trans2txt(file, new_path)
        print("《{}》转换完成".format(file.split('/')[-1].split('.')[0]))


def trans2txt(filename, new_path):
    file = docx.Document(filename)
    paragraphs = []
    for i in range(len(file.paragraphs)):
        paragraphs.append(file.paragraphs[i].text)

    filename = filename.split('/')[-1]
    new_filename = 'dataset/text/' + filename[0:filename.rfind('.')] + '.txt'
    with open(new_filename, 'w', encoding='utf-8') as f:
        for i in range(len(paragraphs)):
            f.write(file.paragraphs[i].text + '\n')


def doc2text(filename):
    temp_file = ''
    if filename.endswith('.doc'):
        fname = filename.split('/')[-1]
        new_filename = fname[0:fname.rfind('.')] + '.txt'
        shutil.copy(filename, new_filename)
        filename = new_filename
        temp_file = new_filename
    with open(filename, 'r', encoding='gbk', errors='ignore') as f:
        new_lines = []
        begin_flag = False
        content_flag = False
        bracket_flag = False
        op_bracket = False
        content = ''
        for c in f.read():
            if c == '<':
                op_bracket = True
                if content_flag:
                    if content.strip().endswith('院'):
                        begin_flag = True
                    if begin_flag:
                        new_lines.append(content.strip())
                    content = ''
                bracket_flag = True
                continue
            if bracket_flag:
                if c == '>':
                    if content_flag:
                        content_flag = False
                    bracket_flag = False
            elif op_bracket:
                content += c
                content_flag = True
        new_lines.pop()
        filename = filename.split('/')[-1]
        new_filename = 'dataset/text/' + filename[0:filename.rfind('.')] + '.txt'
        with open(new_filename, 'w', encoding='utf-8') as new_file:
            for line in new_lines:
                if len(line.strip()) > 0:
                    new_file.write(line.strip() + '\n')
    if os.path.exists(temp_file):
        os.remove(temp_file)


if __name__ == '__main__':
    transFile('docx', 'text')
